package com.dexing.likou;

import java.util.Arrays;

/**
 * 归并排序
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[arr.length];
        mergeSort(arr,0, arr.length-1,temp);
        System.out.println(Arrays.toString(arr));
    }

    //归并排序
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            //向左递归分解
            mergeSort(arr, left, mid, temp);
            //向右递归分解
            mergeSort(arr, mid + 1, right, temp);
            //合并
            merge(arr,left,mid,right,temp);


        }

    }

    /**
     * @param arr   排序的原始数组
     * @param left  左边有序序列的初始索引
     * @param mid   中间索引
     * @param right 右边索引
     * @param temp  中转数组
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;  //左索引
        int j = mid + 1;  //右索引
        int t = 0; //指向temp的当前索引
        //将左右两边的数组按大小拷贝到temp,直到一边到头结束
        while (i <= mid && j <= right) {
            if (arr[i] < arr[j])
                temp[t++] = arr[i++];
            else
                temp[t++] = arr[j++];

        }
        //右边的数组还有剩余的元素,全部移到temp数组
        while (j <= right)
            temp[t++] = arr[j++];
        //左边的数组还有剩余的元素,全部移到temp数组
        while (i <= mid)
            temp[t++] = arr[i++];

        //将temp数组拷贝到arr数组中
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {

            arr[tempLeft++] = temp[t++];

        }


    }
}
